package com.example.personalmediaplay;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import com.example.personalmediaplay.R;

import android.R.color;
import android.R.string;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager.Query;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.gesture.Gesture;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.widget.ImageButton;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.MenuItem;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.MediaController;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.RadioButton;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.VideoView;
@SuppressLint("SdCardPath") public class MediaPlay extends Activity {

	private static final android.widget.RadioGroup.OnCheckedChangeListener OnCheckedChangeListener = null;
	public ImageButton ibtnPlayAndPuase,ibtnStop,ibtnLast,ibtnNext;
	public MediaPlayer MyMediaPlayer,recordMediaPlayer;
	public RadioButton rbtnMusic,rbtnVideo,rbtnRecord;
	public RadioGroup MyRadioGroup;
	public VideoView MyVideoView;
	public SeekBar MySeekBar;
	public TimerTask MyTimerTask;
	public Timer MyTimer;
	public int doubleClickFlag=0;
	public ArrayList<String> MusicList;
	public ArrayList<String> VideoList=new ArrayList(); 
	public ArrayList<String> RecordList=new ArrayList(); 
	public String MediaPath="/sdcard/";
	public int Mediasp=-1;//可播放资源指针
	public TextView MytvScreen,tbTimer;
	public MediaRecorder MyMediaRecorder=new MediaRecorder();
	public Button btnRecording;
	public File file;
	public  int MediaTime=0;
	public  int MediaCureentTime=0;
	public  int RecordTime=0;
	public GestureDetector MyGestureDetector;
	public AudioManager MyAudioManager;
	public int AudioManagerFlag=0;
	public float AudioManagerX=0,AudioManagerY=0;
	public MyVaules sp;
    @SuppressLint("NewApi") @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_media_play);
        sp=(MyVaules)getApplicationContext();//全局变量指针
        
        
        MusicList=new ArrayList<String>();
        //主屏幕显示区域
        MytvScreen=(TextView)findViewById(R.id.MytvScreen);
        MytvScreen.setBackgroundResource(R.drawable.bk);
       
        
        
        //设置显示区域双击事件
        MytvScreen.setOnClickListener(new MyVideoViewOnClickListener());
        //进度条
        MySeekBar=(SeekBar)findViewById(R.id.seekBar1);
        MySeekBar.setOnSeekBarChangeListener(new MySeekBarOnSeekBarChangeListener());	
        //进度条中的显示控件
        tbTimer=(TextView)findViewById(R.id.tbTime);
        tbTimer.setText("");
        //控制按钮
        ibtnPlayAndPuase=(ImageButton)findViewById(R.id.ibtnPlayAndPuase);
        ibtnStop=(ImageButton)findViewById(R.id.ibtnStop);
        ibtnLast=(ImageButton)findViewById(R.id.ibtnLast);
        ibtnNext=(ImageButton)findViewById(R.id.ibtnNext);
        
        ibtnPlayAndPuase.setTag("play");
        ibtnPlayAndPuase.setOnClickListener(new MyImagebtnOnClick());
        ibtnStop.setOnClickListener(new MyImagebtnOnClick());
        ibtnLast.setOnClickListener(new MyImagebtnOnClick());
        ibtnNext.setOnClickListener(new MyImagebtnOnClick());
        //单选按钮组
        rbtnMusic=(RadioButton)findViewById(R.id.rbtnMusic);
        rbtnMusic.setChecked(true);
        rbtnVideo=(RadioButton)findViewById(R.id.rbtnVideo);
        rbtnRecord=(RadioButton)findViewById(R.id.rbtnRecord);
        rbtnRecord.setTag("play");
        MyRadioGroup=(RadioGroup)findViewById(R.id.radioGroup1);
        MyRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO Auto-generated method stub
				ibtnPlayAndPuase.setImageResource(R.drawable.ibtnplay);
				ibtnPlayAndPuase.setTag("play");
				MySeekBar.setMax(10);
				MySeekBar.setProgress(0);
				switch(arg0.getCheckedRadioButtonId())
				{
				case R.id.rbtnMusic:
					if(rbtnMusic.isChecked()==true)
					{
						btnRecording.setVisibility(View.INVISIBLE);
						MytvScreen.setBackgroundResource(R.drawable.bk);
						MytvScreen.setText("暂无歌词");
						if(MyVideoView!=null&&MyVideoView.isPlaying()==true)
							MyVideoView.pause();
					 
						MyMediaPlayer.reset();
						 
						if(MusicList.size()>0)
						{
							Mediasp=-2;
				
						}
						else
							Mediasp=-1;
						try
						{
							Mediasp=(Integer) rbtnMusic.getTag();
							//设置菜单
							 setTitle("音乐播放器");
						}
						catch(Exception e)
						{
							
						}
					}
					  
					break;
				case R.id.rbtnVideo:
					if(rbtnVideo.isChecked()==true)
					  {
						setTitle("视频播放器");
						  MytvScreen.setText("");
						  btnRecording.setVisibility(View.INVISIBLE);
						  MytvScreen.setBackgroundResource(0);
						  if(MyMediaPlayer!=null&&MyMediaPlayer.isPlaying()==true)
							  MyMediaPlayer.pause();
						  if(VideoList.size()>0)
						  {
							  Mediasp=-2;
						  }
						  else
							  Mediasp=-1;
					  }
					break;
				case R.id.rbtnRecord:	
					if(rbtnRecord.isChecked()==true)
					  {
						setTitle("录音器");
						MytvScreen.setText("欢迎使用录音功能!");
						btnRecording.setTag("play");
						btnRecording.setVisibility(View.VISIBLE);
						  MytvScreen.setBackgroundResource(R.drawable.bk);
						  Mediasp=-5;
						  //rbtnMusic.setChecked(false);
						 // rbtnVideo.setChecked(false);
						  if(MyMediaPlayer!=null&&MyMediaPlayer.isPlaying()==true)
							  MyMediaPlayer.pause();
						  if(MyVideoView!=null&&MyVideoView.isPlaying()==true)
							  MyVideoView.pause();
						  if(RecordList.size()>0)
						  {
							  Mediasp=0;
						  }
						  else
							  Mediasp=-1;
					  }
					break;
				
				}
			}

		 
        	
        });
        
        //录音按钮
        btnRecording=(Button)findViewById(R.id.btnRecording);
        btnRecording.setOnClickListener(new MyImagebtnOnClick());
        btnRecording.setTag("play");
        btnRecording.setText(R.string.startRecord);
        btnRecording.setVisibility(View.INVISIBLE);
      
        //获取资源文件创建列表
      //  getFiles(MediaPath, ".mp3", MusicList, false);
        MusicList=sp.getMusicList();
     
        getFiles(MediaPath, ".mp4", VideoList, false);
        getFiles(MediaPath+"MyRecords/", ".amr", RecordList, false);
        //视频播放器
        MyVideoView=(VideoView)findViewById(R.id.videoView1);
        MyVideoView.setOnCompletionListener(new PlayerOnCompletionListener());
        MyVideoView.setOnClickListener(new MyVideoViewOnClickListener());
        MyVideoView.setClickable(true);
        if(VideoList.size()>0)
        {
        	Mediasp=0;
        	MyVideoView.setVideoURI(Uri.parse(VideoList.get(Mediasp)));
      
        }
       //音频播放器
        MyMediaPlayer=new MediaPlayer();
      
        if(MusicList.size()>0)
		{
        	try {
				Mediasp=0;
				MyMediaPlayer.setDataSource(MusicList.get(Mediasp));
				MyMediaPlayer.prepare();
				MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
        
       
        
        MyTimerTask=new TimerTask()
        {
			 @Override
			public void run()
			{
				 //AudioManagerFlag=0;
				doubleClickFlag=0;//tbTimer.setText("开始");
				// TODO Auto-generated method stub
				if(rbtnMusic.isChecked()==true||rbtnRecord.isChecked()==true)
				{
					//if(MyVideoView!=null&&MyVideoView.isPlaying()==false)
						
					if(MyMediaPlayer!=null&&MyMediaPlayer.isPlaying()==true)
					{
						MySeekBar.setMax(MyMediaPlayer.getDuration());
						MySeekBar.setProgress(MyMediaPlayer.getCurrentPosition());
						//tbTimer.setText(getString(MyMediaPlayer.getCurrentPosition())+"/"+getString(MyMediaPlayer.getDuration()));
						
					}
					if(rbtnMusic.isChecked()==true)
					{
						rbtnMusic.setTag(Mediasp);
					}
				}
				else if(rbtnVideo.isChecked()==true)
				{
					
					if(MyVideoView!=null&&MyVideoView.isPlaying()==true)
					{
						//MyVideoView.setAlpha(1);
						MySeekBar.setMax(MyVideoView.getDuration());
						MySeekBar.setProgress(MyVideoView.getCurrentPosition());
					}
				}
				if(btnRecording.getTag()=="Recording")
				{
					RecordTime++;
					
					MySeekBar.setMax(10000);
					MySeekBar.setProgress(RecordTime);
				}
				else
				{
					RecordTime=0;
				}
				
				
			}
		};
		MyTimer=new Timer(true);
		MyTimer.schedule(MyTimerTask, 1000, 1000);
		//MyTimer.cancel();//退出计时器
		
		//设置音量
		MyAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
	    //添加屏幕触发事件
		MyGestureDetector =new GestureDetector(this,new MyGestureDetectorListener());    
		MytvScreen.setOnTouchListener(new OnTouchListener()
				{

					@Override
					public boolean onTouch(View arg0, MotionEvent arg1) {
						// TODO Auto-generated method stub
						//return false;
						return MyGestureDetector.onTouchEvent(arg1);
					}
			
				});
		
		//接受来自页面跳转的信息
		Bundle MyBundle=this.getIntent().getExtras();
		try
		{
			int name=MyBundle.getInt("name");
			switch(name)
			{
			case 1:
				rbtnMusic.setChecked(true);
				break;
			case 2:
				rbtnVideo.setChecked(true);
				break;
			default:
				rbtnRecord.setChecked(true);
				break;
		
			}
			MyRadioGroup.setVisibility(View.INVISIBLE);
			MytvScreen.append(Integer.toString(name));
		}
		catch(Exception e)
		{
			
		}
		//
		
	

		
    }
    
    
    
    
    
    //程序退出之前发生的事件
    @Override 
    protected void onDestroy()
    {
    	super.onDestroy();
    	try
    	{
    		MyMediaPlayer.release();
    		MyVideoView.stopPlayback();
    		MyMediaRecorder.release();
    		MyTimer.cancel();
    	}
    	catch(Exception e)
    	{}
    }
   //自动获取指定目录下文件的方法
    private void getFiles(String dirpath,String fileType,ArrayList<String> List,boolean IsIterative)
    {
    	//List.clear();
    	File[] files = new File(dirpath).listFiles();  
        File f;  
        if(files == null)  
        {  
            return;  
        }  
        for (int i = 0; i < files.length; i++)  
        {  
            f = files[i];  
            if(!f.canRead())  
            {  
            	continue; 
            }  
            if (f.isFile())  
            {  
                if (f.getName().contains(fileType))  //判断扩展名                         
                {  
                	List.add(f.getPath());  
                }  
            }  
            else if (f.isDirectory()&&IsIterative==true)    
            	getFiles(f.getPath(), fileType,List, IsIterative);  
        }
    }
    //触屏事件
    private class MyGestureDetectorListener implements  OnGestureListener,OnDoubleTapListener
    {

		@Override //单击
		public boolean onDown(MotionEvent arg0) {
			// TODO Auto-generated method stub
			//rbtnMusic.setText(R.string.hello_world);
			//MytvScreen.append("\n单击");
			return false;
		}

		@Override//  滑动，触摸屏按下后快速移动并抬起，会先触发滚动手势，跟着触发一个滑动手势 
		public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
				float arg3) {
			// TODO Auto-generated method stub
			//MytvScreen.append("\n滑动");
		
			return false;
		}

		@Override// 长按，触摸屏按下后既不抬起也不移动，过一段时间后触发 
		public void onLongPress(MotionEvent arg0) {
			// TODO Auto-generated method stub
			AudioManagerFlag=0;
			
			//
			try
			{
			if(MyVideoView.isPlaying())
			{
				MyVideoView.pause();
				ibtnPlayAndPuase.setImageResource(R.drawable.ibtnplay);
				ibtnPlayAndPuase.setTag("play");
			}
			Intent i=new Intent();
			i.setClass(MediaPlay.this,MediaList.class);
			Bundle data=new Bundle();
		 
			//调出菜单，第一个参数是列表的类型，第二个参数是当前歌曲在播放离别中的位置
			data.putInt("sp",Mediasp);
			data.putInt("Type",MyRadioGroup.getCheckedRadioButtonId());
			i.putExtras(data);
			startActivityForResult(i,MyRadioGroup.getCheckedRadioButtonId());
			}
			catch(Exception e)
			{
				
			}
			
			
			 
			
			
		}

		@Override// 滚动，触摸屏按下后移动 
		public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
				float arg3) {
			// TODO Auto-generated method stub
			if(AudioManagerFlag==0)
			{
				AudioManagerY=arg0.getY();
				AudioManagerX=arg0.getX();
			}
			int IsSound=0;
			if(AudioManagerFlag>5)
			{
				AudioManagerFlag=0;
				if(((AudioManagerY-arg1.getY())<1)||(arg1.getY()-AudioManagerY<1))
				{
					
					if(arg0.getX()>arg1.getX())//左滑动调小音量
					{
						MyAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,    
	                        AudioManager.FX_FOCUS_NAVIGATION_UP);
					}
					else//右滑动调大音量
					{
						MyAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,    
		                        AudioManager.FX_FOCUS_NAVIGATION_UP); 
						
					}				
				}
			}
			else
			{
				AudioManagerFlag++;
			}
			
			return false;
		}

		@Override// 短按，触摸屏按下后片刻后抬起，会触发这个手势，如果迅速抬起则不会 
		public void onShowPress(MotionEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override// 抬起，手指离开触摸屏时触发(长按、滚动、滑动时，不会触发这个手势) 
		public boolean onSingleTapUp(MotionEvent arg0) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override// 双击，手指在触摸屏上迅速点击第二下时触发 
		public boolean onDoubleTap(MotionEvent arg0) {
			// TODO Auto-generated method stub
			//MytvScreen.append("\n双击 ");
			return false;
		}

		@Override// 双击的按下跟抬起各触发一次 
		public boolean onDoubleTapEvent(MotionEvent arg0) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override// 单击确认，即很快的按下并抬起，但并不连续点击第二下 
		public boolean onSingleTapConfirmed(MotionEvent arg0) {
			// TODO Auto-generated method stub
			//MytvScreen.append("\n单击确认 ");
			return false;
		}}
    
    //读取音乐文件信息并显示出来
    @SuppressWarnings("deprecation")
	@SuppressLint("NewApi") public void getCursorfromPath(String filePath)
    {
        String mpFilename = "";
    	String mpTitle = "";
    	String mpDuration = ""; 
    	String mpArtist = "";
    	String mpAlbum = ""; 
    	String mpAge="";
    	String mpSize = "0";
    	String path = null;
    	String Type="";
    	Cursor cursor=getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media.DATA}
                , MediaStore.Audio.Media.MIME_TYPE+"=? or " + MediaStore.Audio.Media.MIME_TYPE+"=?", new String[]{"audio/mpeg","audio/x-ms-wma"},null);
    	
    	if (cursor.moveToFirst()) {
    		do{
    			 path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
    			 if (path.equals(filePath)) { 
    				  break; 
    			 }
    		}while (cursor.moveToNext());  
    		
    	}
    	mpFilename=cursor.getString(1).toString();//文件名
    	mpTitle = cursor.getString(2).toString(); //歌曲名
    	mpDuration=cursor.getString(3).toString();//时长
    	int Duration=0;
    	try
    	{
    	Duration=Integer.parseInt(mpDuration)/1000;
    	mpDuration=Integer.toString((Duration/60))+":"+Integer.toString(Duration%60);
    	}
    	catch(Exception e)
    	{
    		mpDuration="未知";
    	}
    	mpArtist = cursor.getString(4).toString();//歌手名
    	mpAlbum= cursor.getString(5).toString();//专辑名
    	MytvScreen.setText("\n歌曲名:"+mpTitle);
		 MytvScreen.append("\n歌手名:"+mpArtist);
		 MytvScreen.append("\n专    辑:"+mpAlbum);
		 MytvScreen.append("\n时    长:"+mpDuration);
		//mpSize = cursor.getString(4).toString(); //cursor.getString(5).toString();
		  if (cursor.getString(6) != null) {//年代
			  mpAge=cursor.getString(6);
         } else {
        	 mpAge="未知";
         }
		  MytvScreen.append("\n年    代:"+mpAge);
	     if ("audio/mpeg".equals(cursor.getString(7).trim())) {//歌曲格式
	    	 Type="mp3";
        } else if ("audio/x-ms-wma".equals(cursor.getString(7).trim())) {
        	Type="wma";
        }
        if (cursor.getString(8) != null) {//文件大小
             float temp = cursor.getInt(8) / 1024f / 1024f;
             String sizeStr = (temp + "").substring(0, 4);
             mpSize=sizeStr + "M";
        } else {
        	mpSize="未知";
        }
        MytvScreen.append("\n大    小:"+mpSize); 
        if (cursor.getString(9) != null) {//文件路径
        	path=cursor.getString(9);
        	MytvScreen.append("\n文件名称:"+mpFilename); 
        }
        Bitmap bm = null;  
        if (mpArtist == null) {    
        	MytvScreen.setBackgroundResource(R.drawable.bk);
        } 
        else {    
       
        bm = BitmapFactory.decodeFile(mpArtist);  
        BitmapDrawable bmpDraw = new BitmapDrawable(bm);    
        if(bm!=null)
        	MytvScreen.setBackgroundDrawable(bmpDraw);
        
        }
     	
    }
    
    //播放器播放完成后
    private class PlayerOnCompletionListener implements OnCompletionListener
    {

		@Override
		public void onCompletion(MediaPlayer arg0) {
			// TODO Auto-generated method stub
			ibtnPlayAndPuase.setImageResource(R.drawable.ibtnplay);
			ibtnPlayAndPuase.setTag("play");
			MySeekBar.setProgress(0);
			tbTimer.setText("");
			if(rbtnRecord.getTag()=="trylisten")
			{
				rbtnRecord.setTag("");
				MytvScreen.append("\n试听结束!");
				return;
			}
			setMyIbtn(ibtnNext);
			
			
		}
    	
    }
 //视频播放器双击全频设置
    private class MyVideoViewOnClickListener implements OnClickListener
    {

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(doubleClickFlag==1)
		{
			MytvScreen.append("\n你双击了屏幕");
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			WindowManager winManager=(WindowManager)getSystemService(Context.WINDOW_SERVICE);
			MyVideoView.measure(winManager.getDefaultDisplay().getHeight(), winManager.getDefaultDisplay().getWidth());
			//getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			//MyVideoView.measure(100,100);
		}
		else
		{
		 
		}
		doubleClickFlag=1;
	}}
 
  
    //进度条
    private class MySeekBarOnSeekBarChangeListener implements OnSeekBarChangeListener
    {

  	@Override
  	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  		// TODO Auto-generated method stub
  		if(MyMediaPlayer.isPlaying()==true||MyVideoView.isPlaying()==true)
  		{

  			MediaTime=seekBar.getMax()/1000;
  			MediaCureentTime=seekBar.getProgress()/1000;
  			tbTimer.setText(Integer.toString(MediaCureentTime/60)+":"+Integer.toString(MediaCureentTime%60)+"/"+Integer.toString(MediaTime/60)+":"+Integer.toString(MediaTime%60));
  			if(MyVideoView.isPlaying()==true)
  			{
  				MytvScreen.setText("");
  			}
  			if(MyMediaPlayer.isPlaying()==true)//播放音频时字幕
  			{
  				
  		 
  		       
  			}
  			
  		}
  		else if(btnRecording.getTag()=="Recording")
  		{
  			MediaTime=seekBar.getProgress();
  			tbTimer.setText("录音时长:"+Integer.toString(MediaTime/60)+":"+Integer.toString(MediaTime%60));
  		}
  	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		if(rbtnMusic.isChecked()==true||rbtnRecord.isChecked()==true)
		{
			if(MyMediaPlayer!=null)
			{
				MySeekBar.setMax(MyMediaPlayer.getDuration());
			}
		}
		else
		{
			if(MyVideoView!=null)
			{
				MySeekBar.setMax(MyVideoView.getDuration());
			}
		}
		
	}
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		if(rbtnMusic.isChecked()==true)
		{
			if(MyMediaPlayer!=null)
			{
				MyMediaPlayer.seekTo(MySeekBar.getProgress());
			}
		}
		else
		{
			if(MyVideoView!=null)
			{
				MyVideoView.seekTo(MySeekBar.getProgress());
			}
		}
	}
	  
  }
    
  
   private class MyImagebtnOnClick implements OnClickListener
   {

	   @Override
	   public void onClick(View V) 
	   {
		   // TODO Auto-generated method stub
		   switch(V.getId())
		   {
		   case R.id.ibtnPlayAndPuase:
			   setMyIbtn(ibtnPlayAndPuase);
			   break;
		   case R.id.ibtnStop:
			   setMyIbtn(ibtnStop);
			   break;
		   case R.id.ibtnLast:
			   setMyIbtn(ibtnLast);
			   break;
		   case R.id.ibtnNext:
			   setMyIbtn(ibtnNext);
			   
			   break;
		   case R.id.btnRecording:
			   setMyIbtn(btnRecording);
		   default:
			   break;
		   }
		
	   }
   	}
	//按钮设置的方法集合
	@SuppressLint({ "SdCardPath", "NewApi" }) private void setMyIbtn(View ibtn) 
	{
	
		switch(ibtn.getId())
		{
			case R.id.ibtnPlayAndPuase:
				if(ibtnPlayAndPuase.getTag()=="play")
				{
					    
						if(rbtnMusic.isChecked()==true)
						{
							
							if(MusicList.size()==0)
								{
								return;
								}
							if(Mediasp==-2||Mediasp==-5)
							{
								Mediasp=0;
								//setMyIbtn(ibtnNext);
							}
							try {
								MyMediaPlayer.setDataSource(MusicList.get(Mediasp));
								MyMediaPlayer.prepare();
							} catch (IllegalStateException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							MyMediaPlayer.start();	
							ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
							ibtnPlayAndPuase.setTag("pause");
							try
							{
							getCursorfromPath("/mnt"+MusicList.get(Mediasp));
							}
							catch(Exception e)
							{
								
							}
							//getCursorfromPath("a.mp3");
						   
						}
						else if(rbtnVideo.isChecked()==true)
						{
							if(VideoList.size()==0)
								return;
							if(Mediasp==-2||Mediasp==-5)
							{
								Mediasp=0;
							}
							MyVideoView.start();
							ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
							ibtnPlayAndPuase.setTag("pause");
						}
						else //录音模式
						{
							if(btnRecording.getTag()=="Recording")
								return;
							if(RecordList.size()>0)
							{
								MyMediaPlayer.reset();
								//MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
								try {
									MyMediaPlayer.setDataSource(RecordList.get(Mediasp));
									MyMediaPlayer.prepare();
									MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
								} catch (IllegalArgumentException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (SecurityException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IllegalStateException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								MyMediaPlayer.start();
							 
								ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
								ibtnPlayAndPuase.setTag("pause");
								if(rbtnRecord.getTag()=="trylisten")
								{
									MytvScreen.append("\n正在试听...");
								}
 
							}
						}
				}
				else
				{
					ibtnPlayAndPuase.setImageResource(R.drawable.ibtnplay);
					ibtnPlayAndPuase.setTag("play");
					if(rbtnMusic.isChecked()==true||rbtnRecord.isChecked()==true)
					{
						MyMediaPlayer.pause();
					}
					else if(rbtnVideo.isChecked()==true)
					{
						MyVideoView.pause();
					}
				 
				}
				break;
			case R.id.ibtnStop:
				//MytvScreen.append(Integer.toString(MyMediaPlayer.getAudioSessionId()));
				if(btnRecording.getTag()=="Recording")
					return;
				if(rbtnMusic.isChecked()==true||rbtnRecord.isChecked()==true)
				{
					if(rbtnRecord.getTag()=="trylisten")
					{
						rbtnRecord.setTag("play");
						MytvScreen.append("\n试听中断!");
					}
					if(ibtnPlayAndPuase.getTag()!="play")
					{
						
						MySeekBar.setProgress(0);
						MyMediaPlayer.pause();
						MyMediaPlayer.seekTo(0);
						MyMediaPlayer.pause();
					}
				}
				else if(rbtnVideo.isChecked()==true)
				{
					MyVideoView.seekTo(0);
					MySeekBar.setProgress(0);
					MyVideoView.pause();
					
				}
				ibtnPlayAndPuase.setImageResource(R.drawable.ibtnplay);
				ibtnPlayAndPuase.setTag("play");
				break;
			case R.id.ibtnLast:
				if(rbtnMusic.isChecked()==true)
				{
					if(Mediasp>0&&MusicList.size()>0)
					{
						MyMediaPlayer.reset();
						//MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
						Mediasp--;
						try {
							MyMediaPlayer.setDataSource(MusicList.get(Mediasp));
							MyMediaPlayer.prepare();
							MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						MyMediaPlayer.start();
						try
						{
						getCursorfromPath("/mnt"+MusicList.get(Mediasp));
						}
						catch(Exception e)
						{
							
						}
						ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
						ibtnPlayAndPuase.setTag("pause");
					}
				}
				else if(rbtnVideo.isChecked()==true)
				{
					
					if(Mediasp>0&&VideoList.size()>0)
					{
						Mediasp--;MyVideoView.stopPlayback();
						MyVideoView.setOnCompletionListener(new PlayerOnCompletionListener());
						MyVideoView.setVideoURI(Uri.parse(VideoList.get(Mediasp)));
						MyVideoView.start();
						ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
						ibtnPlayAndPuase.setTag("pause");
					}
				}
				else
				{
					if(btnRecording.getTag()=="Recording")
						return;
					if(Mediasp>0&&RecordList.size()>0)
					{
						MyMediaPlayer.reset();
						//MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
						Mediasp--;
						try {
							MyMediaPlayer.setDataSource(RecordList.get(Mediasp));
							MyMediaPlayer.prepare();
							MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						MyMediaPlayer.start();
					 
						ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
						ibtnPlayAndPuase.setTag("pause");
					}
				}
				break;
			case R.id.ibtnNext:
				
				if(rbtnMusic.isChecked()==true)
				{
					if(Mediasp+1<MusicList.size())
					{Mediasp++;MyMediaPlayer.reset();
					try {
						MyMediaPlayer.setDataSource(MusicList.get(Mediasp));
						MyMediaPlayer.prepare();
						MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					MyMediaPlayer.start();
					try
					{
					getCursorfromPath("/mnt"+MusicList.get(Mediasp));
					}
					catch(Exception e)
					{
						
					}
					ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
					ibtnPlayAndPuase.setTag("pause");
					}
				}
				else if(rbtnVideo.isChecked()==true)
				{
					
					if(Mediasp+1<VideoList.size())
					{
						Mediasp++;MyVideoView.stopPlayback();
						MyVideoView.setVideoURI(Uri.parse(VideoList.get(Mediasp)));
						MyVideoView.start();
						ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
						ibtnPlayAndPuase.setTag("pause");
					}
				}
				else
				{
					if(btnRecording.getTag()=="Recording")
						return;
					if(Mediasp+1<RecordList.size())
					{
						Mediasp++;MyMediaPlayer.reset();
						try {
							MyMediaPlayer.setDataSource(RecordList.get(Mediasp));
							MyMediaPlayer.prepare();
							MyMediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
						} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e) {
					// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
					// TODO Auto-generated catch block
							e.printStackTrace();
						}
						MyMediaPlayer.start();
					 
						ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
						ibtnPlayAndPuase.setTag("pause");
					}
					
				}
				break;
			case R.id.btnRecording:
				if(btnRecording.getTag()=="play")
				{
					//MyMediaRecorder =new MediaRecorder();
					//MyMediaRecorder.reset();
					//MyMediaRecorder.reset();
					if(MyMediaPlayer.isPlaying())
						MyMediaPlayer.pause();
					
					new DateFormat();
					file=new File("/sdcard/MyRecords/"+"bear"+DateFormat.format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA))+".amr");
					File destDir = new File("/sdcard/MyRecords/");
					if (!destDir.exists())
					{
					  destDir.mkdirs();
					}
					MyMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					MyMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
					MyMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
					try {
						file.createNewFile();
						MyMediaRecorder.setOutputFile(file.getAbsolutePath());
						MyMediaRecorder.prepare();
						} catch (IllegalStateException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
						} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
						}
					
					MyMediaRecorder.start();		
					btnRecording.setTag("Recording");
					btnRecording.setText("录音中...");
					MytvScreen.setText("\n录音中......");
					MytvScreen.append("\n保存路径:"+file.getAbsolutePath());
					RecordList.add(0,file.getAbsolutePath());
					Mediasp=0;
				}
				else 
				{
					btnRecording.setText("开始录音");
					//MyMediaRecorder.stop();
					MyMediaRecorder.reset();
					//MyMediaRecorder.release();
					//MyMediaRecorder=null;
					MyMediaRecorder =new MediaRecorder();
					MytvScreen.append("\n录音结束!");
					MytvScreen.append("\n点击播放按钮可试听!");
					btnRecording.setTag("play");
					rbtnRecord.setTag("trylisten");
				}
				break;
			default:
				break;
		}
	}
	
//处理页面跳转返回值
	@Override
	protected void onActivityResult(int requestcode,int resultcode,Intent data)
	{
		
		switch(requestcode)
		{
		case R.id.rbtnMusic://音乐跳转列表
			if(resultcode==1)
			{
				MyMediaPlayer.reset();
				MusicList=sp.getMusicList();
				Mediasp=sp.getMediasp();MytvScreen.append("\nsp:"+Integer.toString(Mediasp)+":"+Mediasp);
				//MyMediaPlayer=new MediaPlayer();
				//
				ibtnPlayAndPuase.setTag("play");
				ibtnPlayAndPuase.performClick();
				
			}
			break;
		case R.id.rbtnVideo://视频跳转列表
			if(resultcode==2)
			{
				//ibtnStop.performClick();
				//MyVideoView.stopPlayback();
				
				VideoList=sp.getVideoList();
				Mediasp=sp.getMediasp();
				MytvScreen.append("\nsp:"+Integer.toString(Mediasp)+":"+Mediasp);
				//MyMediaPlayer=new MediaPlayer();
				MyVideoView.stopPlayback();
				MyVideoView.setVideoURI(Uri.parse(VideoList.get(Mediasp)));
				MyVideoView.start();
				ibtnPlayAndPuase.setImageResource(R.drawable.ibtnpause);
				ibtnPlayAndPuase.setTag("pause");
				
			}
			break;
		case R.id.rbtnRecord://录音跳转列表
			if(resultcode==3)
			{
				MyMediaPlayer.reset();
				RecordList=sp.getRecordList();
				Mediasp=sp.getMediasp();MytvScreen.append("\nsp:"+Integer.toString(Mediasp)+":"+Mediasp);
				//MyMediaPlayer=new MediaPlayer();
				//
				ibtnPlayAndPuase.setTag("play");
				ibtnPlayAndPuase.performClick();
				
			}
			break;
		}
		
	}
	
   //菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.media_play, menu);
        menu.add(0,Menu.FIRST+1, 0, R.string.listMusic);
        menu.add(0,Menu.FIRST+2, 0, R.string.listVideo);
   
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
		switch(item.getItemId())
		{
		case Menu.FIRST+1:
			//MyVideoView.setBackgroundColor(color.transparent);
			return true;
		case Menu.FIRST+2:
			
			return true;
		}
		return super.onOptionsItemSelected(item);
    	
    	
    
    }
    
}
